package blatt7;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;

public class Anwendung {

	static final int X = 500, Y = 500;
	static BufferedImage bi = new BufferedImage(X, Y, BufferedImage.TYPE_INT_RGB);
	static Map<Integer, Long> durations = new HashMap<Integer, Long>();
	static String out = "";

	private static class MyCanvas extends Canvas {
		public void paint(Graphics g) {
			g.fillRect(0, 0, X, Y); 
			g.drawImage(bi, 0, 0, null);
		}
	}

	public static void main(String[] args) {
		// dap.util.printArray()
		try {
			int laenge = 0;
			boolean go = false;

			if (args.length > 0) {
				laenge = Math.abs(Integer.parseInt(args[0]));
				go = (args.length > 1 && args[1].equals("go"));
			} else {
				throw new Exception(
						"Bitte die Länge des Zufallsstrings als ersten Parameter angeben.");
			}

			if (go) {
				for (int i = 1; i <= laenge; i++) {
					durations.put(i, algo(i));
					System.gc();
					
					bi.setRGB(5, 5, 0x000FFF);
				}

				showGui(durations);

			} else {
				algo(laenge);
			}

			System.out.println("Finished." + out);
		} catch (NumberFormatException ex) {
			System.out.println("Bitte nur gültige Nummern eingeben.");
		} catch (Exception ex) {
			System.out.println("Fehler: " + ex.getMessage());
		}

	}

	public static long algo(int laenge) {
		String randStr1 = dap.util.randStr(laenge, new java.util.Random()), randStr2 = dap.util
				.randStr(laenge, new java.util.Random());
		dap.util.startMessung("lcs");
		lcsLaenge(randStr1, randStr2);
		dap.util.stopMessung("lcs");
		out += String
				.format("\nDer lcs für zwei Zufallsstrings mit %s Zeichen dauerte %s Millisekungen",
						laenge, dap.util.getMessung("lcs"));
		return dap.util.getMessung("lcs");
	}

	public static void showGui(Map<Integer, Long> points) {
		JFrame window = new JFrame("Graph");
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setSize(new Dimension(X, Y));

		Canvas jp = new MyCanvas();

		window.setLayout(new BorderLayout());
		window.add(jp);
		window.setVisible(true);

	}

	public static int[][] lcsLaenge(String x, String y) {

		int m = x.length(), n = y.length();
		int[][] C = new int[m][n];

		for (int i = 0; i < m; i++) {
			C[i][0] = 0;
		}

		for (int j = 0; j < n; j++) {
			C[0][j] = 0;
		}

		for (int i = 1; i < m; i++) {
			for (int j = 1; j < n; j++) {
				laengenberechnung(y, x, C, i, j);
			}
		}

		return C;
	}

	private static void laengenberechnung(String y, String x, int[][] C, int i,
			int j) {
		if (x.toCharArray()[i] == y.toCharArray()[j]) {
			C[i][j] = C[i - 1][j - 1] + 1;
		} else {
			if (C[i - 1][j] >= C[i][j - 1]) {
				C[i][j] = C[i - 1][j];
			} else {
				C[i][j] = C[i][j - 1];
			}
		}
	}

}